package com.hks360.car_treasure.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.hks360.car_treasure.R;
import com.hks360.car_treasure.activity.ConnectEquipmentActivity;
import com.hks360.car_treasure.application.MyApplication;
import com.hks360.car_treasure.common.AppConfig;
import com.hks360.car_treasure.common.BaiduMapConfig;
import com.hks360.car_treasure.common.Method;
import com.hks360.car_treasure.common.PrefKey;
import com.hks360.car_treasure.listener.TrakeLocationListener;
import com.hks360.car_treasure.manager.CommonDataManager;
import com.hks360.car_treasure.model.CarLocation;
import com.hks360.car_treasure.model.CarState;
import com.hks360.car_treasure.mvp.equipment.presenter.EquipmentPresenter;
import com.hks360.car_treasure.mvp.equipment.presenter.EquipmentPresenterImpl;
import com.hks360.car_treasure.mvp.equipment.view.EquipmentView;
import com.hks360.car_treasure.socket.CommunicationManager;
import com.hks360.car_treasure.socket.PhoneBandDevice;
import com.hks360.car_treasure.util.CoordConverter;
import com.hks360.car_treasure.util.LogUtil;
import com.hks360.car_treasure.util.MyUtil;
import com.hks360.library.nohttp.CallServer;
import com.hks360.library.util.CommonUtil;
import com.hks360.library.util.PrefUtil;
import com.hks360.library.util.UIUtil;
import com.hks360.library.widget.CheckImageView;
import com.hks360.library.widget.CustomDialog;
import com.hks360.nohttp.Response;

import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;

/**
 * 追踪Fragment
 */
public class TrackFragment extends BaseFragment implements  OnGetGeoCoderResultListener {

    private TextureMapView mTrackMv;
    private CheckImageView mRoadStatusIv;
    private ImageView mMapChangeIv;
    private ImageView mLocationIv;
    private CheckImageView mMapPlusIv;
    private CheckImageView mMapMinusIv;
    private BaiduMap mBaiduMap;
    private boolean isFirstLoc = true;
    private float mZoomLevel;
    private boolean mRoadStatusCheck;
    private boolean mChangeCheck;
    private boolean mLocationCheck;

    private double mLatitude;
    private double mLongitude;
    private static final int accuracyCircleFillColor = 0xAAFFFF88;
    private static final int accuracyCircleStrokeColor = 0xAA00FF00;
    private InfoWindow mInfoWindow;
    private BitmapDescriptor mCurrentMarker;
    private GeoCoder mSearch = null;
    private UiSettings mUiSettings;
    private LatLng mll;
    private LocationClient locClient;

    private final static int GPS = 10;
    private String latitude;
    private String longitude;
    private final static int NOLOGIN = 11;
    private final static int NODEVICE = 12;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case GPS:
                    latitude = "";
                    longitude = "";
                    latitude = AppConfig.mComManager.G_BYTE(mGps,9)*1000000 + AppConfig.mComManager.G_BYTE(mGps,10)*10000 + AppConfig.mComManager.G_BYTE(mGps,11)*100 + AppConfig.mComManager.G_BYTE(mGps,12)+"";
                    longitude = AppConfig.mComManager.G_BYTE(mGps,13)*1000000 + AppConfig.mComManager.G_BYTE(mGps,14)*10000 + AppConfig.mComManager.G_BYTE(mGps,15)*100 + AppConfig.mComManager.G_BYTE(mGps,16) + "";
                    Log.e("resp_result:","latitude==>" + latitude + ",longtitude==>" + longitude);
                    readCurrentLocationSuccess();
                    break;
                case NOLOGIN:
                    setServer();
                    AppConfig.mComManager.loading(Method.getTboxId(), PrefUtil.getString(getContext(), PrefKey.LOGIN_PHONE, ""), PrefUtil.getString(getContext(), PrefKey.LOGIN_PASSWORD, ""));
                    PrefUtil.putString(getContext(), PrefKey.TBOX_ID, Method.getTboxId());
                    break;
                case NODEVICE:
                    try {
                        initMyLocation();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    private void setServer() {
        if(!Method.getServer().isEmpty()){
            AppConfig.mComManager.setADDRESS(Method.getServer().split(":")[0].trim());
            AppConfig.mComManager.setPOT(Integer.valueOf(Method.getServer().split(":")[1].trim()));
            Log.e("RWQ111", Method.getServer().split(":")[0]);
            Log.e("RWQ111",Method.getServer().split(":")[1]);
        }
    }

    private byte[] mGps;

    public void setupView() {
        mTrackMv = UIUtil.findViewById(mRootView, R.id.track_mv);
        mRoadStatusIv = UIUtil.findViewById(mRootView, R.id.trake_roadstatus_iv);
        mMapChangeIv = UIUtil.findViewById(mRootView, R.id.trake_mapchange_iv);
        mLocationIv = UIUtil.findViewById(mRootView, R.id.trake_location_iv);
        mMapPlusIv = UIUtil.findViewById(mRootView, R.id.trake_mapplus_iv);
        mMapMinusIv = UIUtil.findViewById(mRootView, R.id.trake_mapminus_iv);
    }

    private void initMyLocation() throws Exception {
        mTrackMv.showZoomControls(false);
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        if (locClient != null) {
            locClient.stop();
        }
        isFirstLoc = true;
        locClient = new LocationClient(getContext());
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);                                //打开gps
        option.setCoorType("bd09ll");                           //设置坐标类型为bd09ll
        option.setPriority(LocationClientOption.NetWorkFirst);  //设置网络优先
        option.setProdName("locSDKDemo2");                      //设置产品线名称
        option.setScanSpan(5000);                               //定时定位，每隔5秒钟定位一次。
        locClient.setLocOption(option);
        locClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                if (bdLocation == null || mTrackMv == null) {
                    return;
                }
                LogUtil.d(bdLocation.getLatitude() + "," + bdLocation.getLongitude());
                // map view 销毁后不在处理新接收的位置
                LatLng ll = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                mSearch.reverseGeoCode(new ReverseGeoCodeOption()
                        .location(ll));
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(5)
                                // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(BaiduMapConfig.MAP_ROTATE_DEFAULT).latitude(bdLocation.getLatitude())
                        .longitude(bdLocation.getLongitude()).build();
                mBaiduMap.setMyLocationData(locData);
                if (isFirstLoc) {
                    isFirstLoc = false;
                    ll = new LatLng(bdLocation.getLatitude(),
                            bdLocation.getLongitude());
                    MapStatus.Builder builder = new MapStatus.Builder();
                    try{
                        builder.target(ll).zoom(mZoomLevel);
                        MapStatusUpdate mapStatus = MapStatusUpdateFactory.newLatLngZoom(ll,mZoomLevel);
                        mBaiduMap.animateMapStatus(mapStatus);
                    }catch (Exception e){

                    }
                    locClient.stop();
                    //第三处添加
                    if (!CommonUtil.isEmptyStr(Method.getCph())) {
                        TextView textView = new TextView(getContext());
                        textView.setBackgroundResource(R.drawable.popup);
                        textView.setText(Method.getCph());
                        textView.setGravity(Gravity.CENTER);
                        InfoWindow.OnInfoWindowClickListener listener = null;
                        listener = new InfoWindow.OnInfoWindowClickListener() {
                            public void onInfoWindowClick() {
                                mBaiduMap.hideInfoWindow();
                            }
                        };
                        mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(textView), ll, -27, listener);
                        mBaiduMap.showInfoWindow(mInfoWindow);
                    }
                }
            }
        });
        locClient.start();
    }
    public void initData() {
        mUiSettings = mBaiduMap.getUiSettings();
        mSearch = GeoCoder.newInstance();
        mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.car_icon);
        mBaiduMap
                .setMyLocationConfigeration(new MyLocationConfiguration(
                        MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker,
                        accuracyCircleFillColor, accuracyCircleStrokeColor));
        mUiSettings.setScrollGesturesEnabled(true);
        if (CommonUtil.isEmptyStr(Method.getTboxId())) {
            try {
                initMyLocation();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            AppConfig.mComManager.getCarInfo(PrefUtil.getString(getContext(),PrefKey.TBOX_ID,""));
            AppConfig.mComManager.setOnRecvCommunicationListener(new CommunicationManager.OnRecvCommunicationListener() {
                @Override
                public void onRecv_B001(int answerID, byte[] message) {
                    String describeStr = CommunicationManager.getCmdString(message, 18);
                    LogUtil.e("qwe",describeStr);
                    if(describeStr.equals("没有登录")){
                        handler.sendEmptyMessage(NOLOGIN);
                    }
                    if(describeStr.equals("设备不在线")){
                        handler.sendEmptyMessage(NODEVICE);
                    }

                }

                @Override
                public void onRecv_B601(String description) {

                }

                @Override
                public void onRecv_A602(List<String> llr) {

                }

                @Override
                public void onRecv_B500(byte[] message) {

                }

                @Override
                public void onRecv_B208(List<PhoneBandDevice> itemsDevices) {

                }

                @Override
                public void onRecv_CarStatus(byte[] carStatusBytes) {

                }

                @Override
                public void onRecv_Gps(byte[] gpsBytes) {
                    mGps = gpsBytes;
                    Log.e("RWQ", Arrays.toString(mGps));
                    handler.sendEmptyMessage(GPS);
                }

                @Override
                public void onConnectBreak() {

                }

                @Override
                public void onRecv_B208Error() {

                }
            });
        }
    }

    /**
     * 打开绑定设备页
     */
    private void goToBindUser() {
        CommonUtil.openActivity(getContext(), ConnectEquipmentActivity.class);
    }

    public void addListener() {
        mLeftTv.setOnClickListener(this);
        mRightIv.setOnClickListener(this);
        mRoadStatusIv.setOnClickListener(this);
        mMapChangeIv.setOnClickListener(this);
        mLocationIv.setOnClickListener(this);
        mMapPlusIv.setOnClickListener(this);
        mMapMinusIv.setOnClickListener(this);
        mBaiduMap.setOnMyLocationClickListener(new BaiduMap.OnMyLocationClickListener() {
            @Override
            public boolean onMyLocationClick() {
                if (!Method.getCph().isEmpty()) {
                    mBaiduMap.showInfoWindow(mInfoWindow);
                } else {
                    CommonUtil.showToast(getContext(), "车牌号为空！");
                }
                return true;
            }
        });
        mBaiduMap.setOnMapStatusChangeListener(new MyMapStatusChanegeListener());
        mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                }

            }
        });
        mSearch.setOnGetGeoCodeResultListener(this);
    }

    @Override
    public void initView() {
        mZoomLevel = PrefUtil.getFloat(getContext(), PrefKey.ZOOM, BaiduMapConfig.ZOOM_SUPERBIG);
        initTitleBarOfRefresh(R.string.binduser_title, R.string.title_track);
        initDialog(R.string.loading_data);
        setupView();
        mTrackMv.showZoomControls(false);
        mBaiduMap = mTrackMv.getMap();
    }

    @Override
    public void onResume() {
        super.onResume();
//        mTrackMv.onResume();
        initData();
        addListener();
    }

    @Override
    public void onPause() {
        super.onPause();
        mTrackMv.onPause();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_track, null);
        initView();
        return mRootView;
    }

    @Override
    public void viewClick(View v) {
        switch (v.getId()) {
            case R.id.common_titlebar_left_tv:  //连接设备
                goToBindUser();
                break;
            case R.id.common_titlebar_right_iv:    //刷新
                map_refresh();
                break;
            case R.id.trake_roadstatus_iv:  //路况
                road_status();
                break;
            case R.id.trake_mapchange_iv:   //地图状态切换
                map_change();
                break;
            case R.id.trake_location_iv:    //定位跟踪
                location_change();
                break;
            case R.id.trake_mapplus_iv: //放大地图
                map_zoom_plus();
                break;
            case R.id.trake_mapminus_iv:    //缩小地图
                map_zoom_minus();
                break;
        }
    }

    //地图刷新
    private void map_refresh() {
        showLocation(mLatitude, mLongitude);
    }

    //实时路况切换
    private void road_status() {
        mRoadStatusCheck = !mRoadStatusCheck;
        mRoadStatusIv.setChecked(mRoadStatusCheck);
        mBaiduMap.setTrafficEnabled(mRoadStatusCheck);
    }

    //地图状态切换
    private void map_change() {
        mChangeCheck = !mChangeCheck;
        mBaiduMap.setMapType(mChangeCheck ? BaiduMap.MAP_TYPE_SATELLITE : BaiduMap.MAP_TYPE_NORMAL);
    }

    //定位跟踪
    private void location_change() {
        mLocationCheck = !mLocationCheck;
        MyLocationConfiguration.LocationMode currentModel = mLocationCheck ? MyLocationConfiguration.LocationMode.COMPASS : MyLocationConfiguration
                .LocationMode.NORMAL;
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(currentModel, true, null));
    }

    //放大地图
    private void map_zoom_plus() {
        mZoomLevel++;
        showZoom();
    }

    //缩小地图
    private void map_zoom_minus() {
        mZoomLevel--;
        showZoom();
    }

    private void showZoom() {
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.zoom(mZoomLevel);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        zoom_image_status();
    }

    private void zoom_image_status() {
        if (mZoomLevel == mBaiduMap.getMinZoomLevel()) {
            mMapMinusIv.setEnabled(false);
        } else if (mZoomLevel == mBaiduMap.getMaxZoomLevel()) {
            mMapPlusIv.setEnabled(false);
        } else {
            mMapMinusIv.setEnabled(true);
            mMapPlusIv.setEnabled(true);
        }
    }
    public void readCurrentLocationSuccess() {
        mLatitude = MyUtil.getBaiduLatitudeOrLongitude(latitude);
        mLongitude = MyUtil.getBaiduLatitudeOrLongitude(longitude);
        showLocation(mLatitude, mLongitude);
    }

    private void showLocation(double latitude, double longitude) {

        locClient = new LocationClient(getContext());
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(BaiduMapConfig.OPEN_GPS);// 打开gps
        option.setCoorType(BaiduMapConfig.COOR_TYPE); // 设置坐标类型
        option.setScanSpan(BaiduMapConfig.SCAN_SPAN);//设置坐标类型为bd09ll
        option.setPriority(LocationClientOption.NetWorkFirst);
        option.setProdName("locSDKDemo2");                      //设置产品线名称
        option.setScanSpan(5000);
        locClient.setLocOption(option);

        locClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                initCurrentLoaction();
            }
        });
        locClient.start();
        mll = new LatLng(latitude, longitude);
    }

    private void initCurrentLoaction() {
        if (mll.latitude != 0 && mll.longitude != 0) {
            CoordinateConverter converter = new CoordinateConverter();
            converter.from(CoordinateConverter.CoordType.GPS);
            // sourceLatLng待转换坐标
            converter.coord(mll);
            mll = converter.convert();
            LogUtil.d("latitude==>" + mll.latitude + ",longitude==>" + mll.longitude);
            try {
                mBaiduMap.setMyLocationEnabled(true);

                // 反Geo搜索
                mSearch.reverseGeoCode(new ReverseGeoCodeOption()
                        .location(mll));
                //第三处添加
                TextView textView = new TextView(getContext());
                textView.setBackgroundResource(R.drawable.popup);
                textView.setText(Method.getCph());
                textView.setGravity(Gravity.CENTER);
                InfoWindow.OnInfoWindowClickListener listener = null;
                listener = new InfoWindow.OnInfoWindowClickListener() {
                    public void onInfoWindowClick() {
                        mBaiduMap.hideInfoWindow();
                    }
                };
                mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(textView), mll, -27, listener);
                if (!Method.getCph().isEmpty()) {
                    mBaiduMap.showInfoWindow(mInfoWindow);

                }
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(5)
                                // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(BaiduMapConfig.MAP_ROTATE_DEFAULT).latitude(mll.latitude)
                        .longitude(mll.longitude).build();
                mBaiduMap.setMyLocationData(locData);
                locClient.stop();
                initZoom(mll.latitude, mll.longitude);
            } catch (Exception e) {
            }
        } else {
            try {
                initMyLocation();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void initZoom(double latitude, double longitude) throws Exception {
        LatLng ll = new LatLng(latitude, longitude);
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(ll).zoom(mZoomLevel);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        if (reverseGeoCodeResult != null) {
            PrefUtil.putString(MyApplication.getInstance(), PrefKey.LOCATION, reverseGeoCodeResult.getAddress());
        }
    }

    private class MyMapStatusChanegeListener implements BaiduMap.OnMapStatusChangeListener {
        public MyMapStatusChanegeListener() {

        }

        @Override
        public void onMapStatusChangeStart(MapStatus mapStatus) {
        }

        @Override
        public void onMapStatusChange(MapStatus mapStatus) {

        }

        @Override
        public void onMapStatusChangeFinish(MapStatus mapStatus) {
            mZoomLevel = mapStatus.zoom;
            zoom_image_status();
        }
    }

    @Override
    public void onDestroyView() {
        Log.e("step", "onDestroyView");
        PrefUtil.putFloat(getContext(), PrefKey.ZOOM, mZoomLevel);
        mTrackMv.onDestroy();
        super.onDestroyView();
    }
}